package com.google.coffeeshop.gui.desktop.receiptnote;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
import java.util.Locale;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import vn.bang.utility.FileUtil;
import vn.bang.utility.LongUtil;

import com.google.coffeeshop.business.AvailabilityBusiness;
import com.google.coffeeshop.business.LoadingBusiness;
import com.google.coffeeshop.business.ManagerBusiness;
import com.google.coffeeshop.business.OrderBusiness;
import com.google.coffeeshop.entity.ProductDTO;
import com.google.coffeeshop.entity.ReceiptNoteDTO;
import com.google.coffeeshop.entity.ReceiptNoteLineDTO;
import com.google.coffeeshop.gui.desktop.SwingFactory;
import com.google.coffeeshop.gui.desktop.selfcomponent.ImagePanel;
import com.google.coffeeshop.gui.desktop.selfcomponent.LRItem;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

public class AddEditReceiptNoteLineFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	
	private JTextField tfQuantity;
	private ImagePanel pnlImage;
	private String image_filename = SwingFactory.NO_IMAGE_NAME;
	private Long receiptNoteLineId = null;
	private AddViewReceiptNoteFrame frmAddViewReceiptNote;
	private JComboBox<LRItem> cbbProduct;
	private ReceiptNoteDTO receiptNote;
	private List<ProductDTO> listProducts;
	private JTextField tfPrice;
	
	/**
	 * Create the panel.
	 */
	public AddEditReceiptNoteLineFrame(AddViewReceiptNoteFrame frmAddViewReceiptNote, ReceiptNoteDTO receiptNote, ReceiptNoteLineDTO receiptNoteLine) {
		this.frmAddViewReceiptNote = frmAddViewReceiptNote;
		this.receiptNote = receiptNote;
		this.receiptNoteLineId = receiptNoteLine != null ? receiptNoteLine.getId() : null;
		setSize(600, 335);
		
		getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(75dlu;default)"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(39dlu;default)"),
				ColumnSpec.decode("max(7dlu;default)"),
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("max(121dlu;default):grow"),
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,},
			new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("max(31dlu;default)"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,}));
		
		JLabel lblAddNewEmployee = new JLabel();
		String text = receiptNoteLine == null ? "Add New Recept Line" : "Edit Recept Line";
		lblAddNewEmployee.setText(text);
		lblAddNewEmployee.setFont(new Font("Tahoma", Font.PLAIN, 16));
		lblAddNewEmployee.setHorizontalAlignment(SwingConstants.CENTER);
		getContentPane().add(lblAddNewEmployee, "2, 2, 9, 1, center, default");
		
		pnlImage = SwingFactory.createImagePanel(Boolean.TRUE);
		pnlImage.setImage(FileUtil.getRelativePathFromProjectPath("employee_images\\" + SwingFactory.NO_IMAGE_NAME));
		getContentPane().add(pnlImage, "2, 4, 1, 13, fill, fill");
		
		JButton btnAdd = new JButton(receiptNoteLine == null ? "Add" : "Save");
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateOrAddEmployee();
			}
		});
		
		JLabel lblProduct = new JLabel("Product");
		getContentPane().add(lblProduct, "4, 8, right, default");
		
		cbbProduct = new JComboBox<LRItem>();
		cbbProduct.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				LRItem item = (LRItem)e.getItem();
				changeProduct(item);
			}
		});
		getContentPane().add(cbbProduct, "7, 8, fill, default");
		
		JLabel lblQuantity = new JLabel("Quantity");
		getContentPane().add(lblQuantity, "4, 10, right, default");
		
		tfQuantity = new JTextField("1");
		getContentPane().add(tfQuantity, "7, 10, fill, default");
		tfQuantity.setColumns(10);
		
		JLabel lblPrice = new JLabel("Price");
		getContentPane().add(lblPrice, "4, 12, right, default");
		
		tfPrice = new JTextField();
		getContentPane().add(tfPrice, "7, 12, fill, default");
		tfPrice.setColumns(10);
		getContentPane().add(btnAdd, "2, 20, 6, 1, fill, fill");
		
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				disposeFrame();
			}
		});
		getContentPane().add(btnCancel, "10, 20, fill, fill");
		
		setProductModel();
		cbbProduct.setSelectedIndex(0);
		if (receiptNoteLine != null) {
			setReceiptNoteLine(receiptNoteLine);
		}
	}
	
	private void refreshParentGUI() {
		frmAddViewReceiptNote.refreshReceiptNoteLineTable();
	}
	
	private void setReceiptNoteLine(ReceiptNoteLineDTO receiptNoteLine) {
		cbbProduct.setSelectedItem(getItemFromProductId(receiptNoteLine.getProduct().getId()));
		tfQuantity.setText(String.valueOf(receiptNoteLine.getQuantity()));
		tfPrice.setText(String.valueOf(receiptNoteLine.getPriceOfUnit()));
		pnlImage.setImage(FileUtil.getRelativePathFromProjectPath("employee_images\\" + receiptNoteLine.getProduct().getImageFilename()));
	}
	
	private LRItem getItemFromProductId(long productId) {
		for (int index = 0; index < cbbProduct.getModel().getSize(); index++) {
			LRItem item = cbbProduct.getModel().getElementAt(index);
			if (LongUtil.parseLong(item.getLeftText()) == productId) {
				return item;
			}
		}
		return null;
	}
	
	private ReceiptNoteLineDTO getReceiptNoteLineDTO() {
		ReceiptNoteLineDTO receiptNoteLine = getReceiptLineFromReceiptNote(receiptNote, receiptNoteLineId);
		receiptNoteLine.setProduct(getProductFromItem((LRItem)cbbProduct.getSelectedItem()));
		receiptNoteLine.setPriceOfUnit(LongUtil.parseLong(tfPrice.getText()));
		receiptNoteLine.setQuantity(LongUtil.parseLong(tfQuantity.getText()));
		receiptNoteLine.setReceiptNote(receiptNote);
		
		return receiptNoteLine;
	}
	
	private ReceiptNoteLineDTO getReceiptLineFromReceiptNote(ReceiptNoteDTO receiptNote, Long receiptNoteLineId) {
		if (receiptNoteLineId != null) {
			for (ReceiptNoteLineDTO receiptNoteLine : receiptNote.getReceiptNoteLines()) {
				if (receiptNoteLine.getId() == receiptNoteLineId) {
					return receiptNoteLine;
				}
			}
		}
		ReceiptNoteLineDTO newReceiptNoteLine = new ReceiptNoteLineDTO();
		receiptNote.getReceiptNoteLines().add(newReceiptNoteLine);
		return newReceiptNoteLine;
	}
	
	private ProductDTO getProductFromItem(LRItem item) {
		long productId = LongUtil.parseLong(item.getLeftText());
		return OrderBusiness.findProduct(productId);
	}
	
	private void changeProduct(LRItem item) {
		long productId = LongUtil.parseLong(item.getLeftText());
		ProductDTO product = OrderBusiness.findProduct(productId);
		pnlImage.setImage(FileUtil.getRelativePathFromProjectPath("/src/main/java/com/google/coffeeshop/gui/desktop/images/products/" + product.getImageFilename()));
	}
	
	private void updateOrAddEmployee() {
		ReceiptNoteLineDTO modifiedReceiptNoteLine = getReceiptNoteLineDTO();
		AvailabilityBusiness.saveReceiptNote(receiptNote);
		ManagerBusiness.saveReceiptNoteLine(modifiedReceiptNoteLine);
		refreshParentGUI();
		disposeFrame();
	}
	
	private void disposeFrame() {
		this.dispose();
	}
	
	private void setProductModel(){
		DefaultComboBoxModel<LRItem> model = new DefaultComboBoxModel<LRItem>();
		listProducts = LoadingBusiness.getAllProducts();
		for(ProductDTO product: listProducts){
			model.addElement(new LRItem(String.valueOf(product.getId()), product.getName()));	
		}
		cbbProduct.setModel(model);
	}
	
	private Locale getLocale(String locate) {
		if(locate!=null && locate.length()>0)
			return new Locale(locate);
		else return Locale.FRANCE;
	}
}
